﻿using System;
using System.Windows;
using System.Windows.Input;

namespace MyEditor
{
    public partial class SearchDialog : Window
    {
        public string Keyword => InputTextBox.Text;
        public event Action<string> OnSearchNext;

        public SearchDialog()
        {
            InitializeComponent();
            Loaded += (s, e) => Refocus();
        }

        public void Refocus()
        {
            InputTextBox.Focus();
            InputTextBox.CaretIndex = InputTextBox.Text.Length;
        }

        public void SetStatus(string msg)
        {
            StatusText.Text = string.IsNullOrEmpty(msg) ? "按回车查找下一个，Esc 关闭" : msg;
        }

        private void InputTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            // 回车 enter 事件
            if (e.Key == Key.Enter)
            {
                OnSearchNext?.Invoke(Keyword);
                // 关键：自己“吞掉”回车，不让它冒泡到主窗口/编辑器
                e.Handled = true;

                // 回车后立即把焦点拉回输入框，避免焦点跑到编辑器
                // （MainWindow 里也会调用 Refocus，这里再保险一次）
                Refocus();
            }
            else if (e.Key == Key.Escape)
            {
                Close();
            }
        }
    }
}